package com.jianjian.system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jianjian.common.utils.RouterHelper;
import com.jianjian.model.system.SysMenu;
import com.jianjian.model.system.SysRole;
import com.jianjian.model.system.SysRoleMenu;
import com.jianjian.model.system.SysUserRole;
import com.jianjian.model.vo.AssginMenuVo;
import com.jianjian.model.vo.RouterVo;
import com.jianjian.system.handler.GuiGuException;
import com.jianjian.system.mapper.SysMenuMapper;
import com.jianjian.system.mapper.SysRoleMenuMapper;
import com.jianjian.system.mapper.SysUserRoleMapper;
import com.jianjian.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author cool
 * @since 2022-11-07
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    //菜单列表(树形架构)
    @Override
    public List<SysMenu> findMenuNodes() {
        List<SysMenu> menuList = baseMapper.selectList(null);//1.查询所有菜单数据

        List<SysMenu> list =  menuList.stream().filter(menu->
           menu.getParentId().longValue() == 0  //2.查询所有一级菜单
        ).map(menu->{
           menu.setChildren(getChildren(menu,menuList));//3.递归查询
            return  menu;
        }).collect(Collectors.toList());

        return list;
    }

    //根据角色获取菜单
    @Override
    public List<SysMenu> findMenuByRoleId(Long roleId) {
        //获取所有菜单 status=1
        List<SysMenu> menuList = baseMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 1));

        //根据角色id查询分配过的菜单
        List<SysRoleMenu> roleMenuList = sysRoleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));

        //获取所有角色分配的菜单id
        List<String> ids =  roleMenuList.stream().map(roleMenu->{
            return roleMenu.getMenuId();
        }).collect(Collectors.toList());

        //设置isSelect是否被选中，选中为true
        menuList.forEach(menu->{
            if (ids.contains(menu.getId())){
                menu.setSelect(true);
            }else {
                menu.setSelect(false);
            }
        });

        //转换成属性结构为了最终显示
        return menuList.stream().filter(menu->
                menu.getParentId().longValue() == 0
        ).map( menu->{
            menu.setChildren(getChildren(menu,menuList));
            return menu;
        }).collect(Collectors.toList());

    }

    //给角色分配权限
    @Override
    public void doAssign(AssginMenuVo assginMenuVo) {
            //根据角色id删除菜单权限
            QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
            sysRoleMenuMapper.delete(wrapper.eq("role_id",assginMenuVo.getRoleId()));

            //遍历新增的菜单集合添加菜单权限
            assginMenuVo.getMenuIdList().forEach(menuId->{
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(assginMenuVo.getRoleId());
                roleMenu.setMenuId(menuId);
                sysRoleMenuMapper.insert(roleMenu);
            });

    }

    /**
     * 递归查询所有子菜单
     * @param sysMenu 上级菜单对象
     * @param menuList  所有菜单集合
     * @return
     */
    private List<SysMenu> getChildren(SysMenu sysMenu, List<SysMenu> menuList) {
      List<SysMenu> list = menuList.stream().filter(menu ->

              menu.getParentId().equals(Long.parseLong(sysMenu.getId()))//查询所有二级菜单
      ).map(menu ->{
                    menu.setChildren(getChildren(menu,menuList));//查询二级菜单下的子菜单
          return menu;

        }).collect(Collectors.toList());

        return list;
    }

    //根据用户id查询菜单权限值
    @Override
    public List<RouterVo> getMenuByUserId(String userId) {
        //admin是超级管理员，操作所有内容
        List<SysMenu> menuList = null;
        //判断userid值是1代表是超级管理员，查询所有权限数据
        if ("1".equals(userId)){
         menuList =  this.list(new QueryWrapper<SysMenu>().orderByAsc("sort_value"));

        }else {
        //如果userid不是1，是其他类型用户，查询这个用户权限
        menuList = baseMapper.findMenuByUserId(userId);
        }
        //构建树形结构数据
        menuList = TreeBuild(menuList);
        return RouterHelper.buildRouters(menuList);
    }
    //构建树形结构数据
    private List<SysMenu> TreeBuild(List<SysMenu> menuList) {
       return menuList.stream().filter(menu->
                menu.getParentId() == 0
        ).map(menu->{
            menu.setChildren(getChildren(menu,menuList));
            return menu;
        }).collect(Collectors.toList());
    }

    //根据用户id查询按钮权限值
    @Override
    public List<String> getButtonByUserId(String userId) {
        List<SysMenu> menuList = null;
        //判断当前用户是否为超级管理员admin
        if ("1".equals(userId)){
            //如果是超级管理员则查询所有按钮权限值
           menuList = this.list(new QueryWrapper<SysMenu>().eq("status",1));
        }else {
            //查询这个用户的所有按钮权限值
            menuList = baseMapper.findMenuByUserId(userId);
        }
        //menuList遍历
        return menuList.stream().filter(menu->
                menu.getType() == 2 //按钮类型
        ).map(menu->
         menu.getPerms()
        ).collect(Collectors.toList());
    }

}
